package cn.lg.soar.database.handler;

import cn.lg.soar.common.util.current.ICurrentUser;
import cn.lg.soar.common.util.current.UserContext;
import cn.lg.soar.database.base.entity.ITenantEntity;
import com.baomidou.mybatisplus.core.metadata.TableInfo;
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
import com.baomidou.mybatisplus.extension.plugins.handler.TenantLineHandler;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.LongValue;
import org.springframework.util.ConcurrentReferenceHashMap;

import java.util.Map;

/**
 * @author luguoxiang 469599794@qq.com
 * @Date: 2024/2/29 8:56
 * 开源项目：https://gitee.com/lgx1992/lg-soar 求star！请给我star！请帮我点个star！
 */
public class SoarTenantLineHandler implements TenantLineHandler {
    private final Map<String, Boolean> IGNORE_TABLES = new ConcurrentReferenceHashMap<>();
    private final static LongValue LONG_VALUE = new LongValue(0);

    @Override
    public String getTenantIdColumn() {
        return ITenantEntity.COLUMN;
    }
    @Override
    public Expression getTenantId() {
        ICurrentUser user = UserContext.getUserNullable();
        if (user == null) {
            return LONG_VALUE;
        }
        Integer tenantId = user.getCurrentTenantId();
        if (tenantId == null) {
            return LONG_VALUE;
        }
        return new LongValue(tenantId);
    }
    @Override
    public boolean ignoreTable(String tableName) {
        return IGNORE_TABLES.computeIfAbsent(tableName, k -> {
            TableInfo tableInfo = TableInfoHelper.getTableInfo(k);
            if (tableInfo == null) {
                return true;
            }
            Class<?> entityType = tableInfo.getEntityType();
            return !ITenantEntity.class.isAssignableFrom(entityType);
        });
    }
}
